﻿#region

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using BusinessObjects;

#endregion

namespace DataAccessLayer
{
    public static class DistrictDAL
    {
        private static readonly string ConnectionString =
            ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

        /// <summary>
        ///     Get All districts
        /// </summary>
        /// <returns>All available districts</returns>
        public static List<District> GetAllDistricts()
        {
            var districts = new List<District>();
            using (var connection = new SqlConnection(ConnectionString))
            {
                var command = new SqlCommand("spGetAllDistricts", connection)
                {
                    CommandType = CommandType.StoredProcedure
                };

                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var district = new District
                        {
                            DistrictId = Convert.ToByte(reader["DistrictId"]),
                            Name = reader["Name"].ToString()
                        };
                        districts.Add(district);
                    }
                }
            }
            return districts;
        }

        /// <summary>
        ///     Get district name by district id
        /// </summary>
        /// <param name="districtId">Represent's the district Id</param>
        /// <returns>District name</returns>
        public static string GetDistrict(byte districtId)
        {
            using (var connection = new SqlConnection(ConnectionString))
            {
                var command = new SqlCommand("spGetDistrictNameById", connection)
                {
                    CommandType = CommandType.StoredProcedure
                };

                command.Parameters.AddWithValue("@DistrictId", districtId);

                connection.Open();
                object district = command.ExecuteScalar();
                return district == null ? null : district.ToString();
            }
        }
    }
}